<template>
	<my-main title="登录" >
		<up-form labelPosition="top" labelWidth="auto" :model="formData" ref="refForm" :rules="rules">
			<my-form-item label="手机号" prop="CellPhone">
				<up-input placeholder="请输入手机号" v-model="formData.CellPhone" @change="change_phone"></up-input>
			</my-form-item>
			<my-form-item label="验证码" prop="Random">
				<up-input placeholder="请输入验证码" v-model="formData.Random">
					<template #suffix>
						<up-button @click="getCode" :text="randomText" type="primary" size="mini" :disabled="!formData.CellPhone || !isRandom"></up-button>
					</template>
				</up-input>
			</my-form-item>
			<view class="m-t-16">
				<my-button @click="onFormSubmit" :disabled="!formData.CellPhone || !formData.Random || !formData.OpenId">登录</my-button>
			</view>
		</up-form>
	</my-main>
	<view class="login-loading" v-if="isLoading">
		<image class="login-img" src="/static/default-share.jpg"></image>
	</view>
</template>

<script lang="uts" setup>
import { useVue } from '@/utils/useVue.uts'
const { reactive,watch, ref, onMounted, goToPage,http, user, OpenId,Token,rulesPhone } = useVue()


// 表单数据
const formData = reactive({
    CellPhone: '',   // 手机号
    Random: '',  // 验证码
    OpenId: ''       ,// 用户ID（备用字段）
	UserName: '',
	Password: '',
})

// 验证码相关状态
const isLoading = ref(true)
const refForm = ref(null)
const isRandom = ref(true)
const randomText = ref('获取验证码')

// 获取验证码
const change_phone = () => {
	formData.Random = ''
}
// 获取验证码
const getCode = () => {
	uni.showToast({
		title: '正在获取验证',
		icon: 'success',
		duration: 2000
})
  http.request({
    url: 'api/MicroProj/GetRandomNumMin',
    data: {
      CellPhone: formData.CellPhone,
      IsStaticCode: true // 本地测试用 true，生产环境应为 false
    },
    isNotToken: true,
    success: (res: any) => {
      if (res) {
	    setCountdown()
		uni.showToast({
			title: '验证码已发送',
			icon: 'none',
			duration: 2000
		})
        formData.Random = res || ''
      }
    },
	fail:(err:any)=>{
		formData.CellPhone=''
	}
  })
}

// 倒计时控制
const setCountdown = (number: number = 60) => {
  isRandom.value = false
  randomText.value = `倒计时${number}S`
  const countdownInterval = setInterval(() => {
    number--
    if (number <= 0) {
      clearInterval(countdownInterval)
      isRandom.value = true
      randomText.value = '获取验证码'
    } else {
      randomText.value = `倒计时${number}S`
    }
  }, 1000)
}
// 校验规则
const rules = {
  CellPhone: [
    {
      required: true,
     message: '请输入手机号',
      trigger: ['blur', 'change'],
    },
	{
		// 自定义验证函数，见上说明
		validator: (rule, value, callback) => {
			// 上面有说，返回true表示校验通过，返回false表示不通过
			// uni.$u.test.mobile()就是返回true或者false的
			return rulesPhone(value);
		},
		message: '手机号码不正确',
		// 触发器可以同时用blur和change
		trigger: ['change','blur'],
	}
  ],
  Random: [
    {
      required: true,
	  message: '请输入验证码',
      trigger: ['blur', 'change'],
    },

  ],
};
//提交登录
const onFormSubmit=()=>{
	if (refForm.value) {
		console.log(refForm.value.validate());
	    refForm.value.validate()
		.then(valid => {
			if (valid) {
				http.request({
					url: 'api/MicroProj/BindMiniUserPhoneOpenid',
					data: {
						CellPhone:formData.CellPhone,
						Random:formData.Random,
						OpenId:formData.OpenId,
					},
					isNotToken: true,
					success: (res : any) => {
						setToken(res.Token)
					}
				 })
				 function setToken(Token:string){
					 if(!Token){
						 console.error('获取token失败')
						 return
					 }
					 //缓存token
					 uni.setStorageSync('Token', Token)
					 //进入首页
					goToPage('home')
				 }
			} else {
			}
		})
		.catch(() => {

			// 处理验证错误
		});  ;
	  }

}
import { getToken  } from '@/utils/auth.uts'
// 登录处理方法（待完善）
const loginUser = async () => {
	getToken({
		success:(res,openId)=>{
			formData.OpenId=openId
			//解绑用户Id
			// console.log('开始解绑');
			// http.request({
			// 	url: 'api/MicroProj/UnBindMiniUserPhoneOpenid',
			// 	data: {
			// 		OpenId:openId,
			// 	},
			// 	isNotToken: true,
			//  })
			user.setUser({})
			goToPage('home')
		},
		fail:(err:any,openId:string)=>{
			formData.OpenId=openId
			if(err.RespMsg?.includes('找不到')){
				http.request({
					url: 'api/MicroProj/UnBindMiniUserPhoneOpenid',
					data: {
						OpenId:openId,
					},
					isNotToken: true,
					success: (res : any) => {
						isLoading.value=false
					},
					fail:()=>{
						formData.OpenId=openId
						isLoading.value=false
					}
				 })
			}else{
				isLoading.value=false
			}
		}
	})

}

onMounted(() => {
	loginUser()
})
</script>

<style scoped lang="scss">
.foot {
	position: absolute;
	left: 32rpx;
	right: 32rpx;
	bottom: 32rpx;
}
.login-loading {
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	z-index: 2;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	.login-img {
		width: 640rpx;
		height: 640rpx;
	}
}
</style>
